<template>
  <div class="zixun">
    <div class="header t-right">
      <el-button type="primary"
                 @click="handleAdd">新增资讯</el-button>
    </div>
    <el-table :data="ziXunList"
              v-loading="loading"
              style="width: 100%">
      <el-table-column prop="title"
                       label="咨询名称">
      </el-table-column>
      <el-table-column prop="content"
                       label="资讯内容">
      </el-table-column>
      <el-table-column prop="createTime"
                       width="180"
                       label="创建时间">
      </el-table-column>
      <el-table-column label="资讯图片地址"
                       tooltip-effect="dark"
                       width="150">
        <template slot-scope="scope">
          <a :href="scope.row.imageUrl"
             target="_Blank">{{scope.row.title}}</a>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       width="150">
        <template slot-scope="scope">
          <el-button size="mini"
                     plain
                     type="primary"
                     @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini"
                     type="danger"
                     @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination layout="total,prev, pager, next"
                   @current-change="handleCurrentChange"
                   background
                   :total="total">
    </el-pagination>

    <!-- 修改客户基础信息 -->
    <el-dialog :title="isEdit?'编辑资讯':'新增资讯'"
               :before-close="onCancel"
               :close-on-click-modal="false"
               :visible.sync="dialogVisible"
               width="500px">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               label-width="50px">
        <el-form-item label="标题"
                      prop="title">
          <el-input clearable
                    placeholder="请输入资讯标题"
                    v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="内容"
                      prop="content">
          <el-input clearable
                    placeholder="请输入资讯内容"
                    v-model="form.content"></el-input>
        </el-form-item>

      </el-form>
      <el-upload class="upload-demo"
                 :headers="{'Authorization': $store.state.app.token}"
                 action="/file/uploadFile"
                 :limit="1"
                 :on-success="handleSuccess"
                 :on-remove="handleRemove"
                 :file-list="fileList"
                 accept=".jpg,.png,.bmp,.jpeg"
                 list-type="picture">
        <el-button size="small"
                   type="primary">点击上传</el-button>
        <div slot="tip"
             class="el-upload__tip">只能上传jpg/png文件</div>
      </el-upload>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary"
                   @click="onSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getZiXunList, deleteZiXun, addZiXun, updateZiXun } from '@/services/service_ziXun'
const initForm = () => {
  return {
    title: '',
    imageId: '',
    content: ''
  }
}
export default {
  name: "zixun",
  data () {
    return {
      loading: false,
      ziXunList: [],
      current: 1, //页码
      size: 10,//条数
      total: 0,
      // 弹窗
      dialogVisible: false,
      isEdit: false,
      form: initForm(),
      rules: {
        title: [
          { required: true, message: '请输入资讯标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入资讯内容', trigger: 'blur' },
        ]
      },
      fileList: []
    }
  },
  methods: {
    onFeach () {
      this.getZiXunListAll({
        current: this.current,
        size: this.size
      })
    },
    async getZiXunListAll (data) {
      this.loading = true
      const res = await getZiXunList(data)
      if (res.code == 0) {
        this.ziXunList = res.data.records
        this.total = res.data.total
        this.loading = false
      } else {
        this.$message.warning(res.msg)
        this.loading = false
      }
    },
    handleCurrentChange (val) {
      this.current = val
      this.onFeach()
    },
    // 删除
    handleDelete (index, row) {
      this.$confirm('此操作将永久删除该资讯, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteZiXun(row.id)
        if (res.code == 0) {
          this.$message.success('删除成功')
          this.onFeach()
        } else {
          this.$message.warning(res.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 修改
    handleEdit (index, row) {
      // console.log(row);
      const { id, imageId, imageUrl, title, content } = row
      this.form = {
        id,
        imageId,
        title,
        content
      }
      this.fileList = [{ name: title, url: imageUrl }]
      this.isEdit = true
      this.dialogVisible = true
    },
    // 添加按钮
    handleAdd () {
      this.isEdit = false
      this.dialogVisible = true
    },
    // 添加，编辑
    onSubmit (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (!this.form.imageId) {
            return this.$message.warning('请上传资讯图片')
          }
          if (!this.isEdit) {
            const res = await addZiXun(this.form)
            if (res.code == 0) {
              this.$message.success('新增成功')
              this.onCancel()
              this.onFeach()
            } else {
              this.$message.warning(res.msg)
            }
          } else {
            const res = await updateZiXun(this.form)
            if (res.code == 0) {
              this.$message.success('更新成功')
              this.onCancel()
              this.onFeach()
            } else {
              this.$message.warning(res.msg)
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel () {
      this.dialogVisible = false
      this.form = initForm()
      this.fileList = []
    },
    // 移除图片
    handleRemove (file, fileList) {
      console.log(file, fileList);
      if (!fileList.length) {
        this.form.imageId = ''
      }
    },
    handleSuccess (response, file, fileList) {
      const { id } = response.data
      this.form.imageId = id
    }
  },
  created () {
    this.onFeach()
  }
}
</script>

<style scoped lang="scss">
.zixun {
  ::v-deep .el-upload-list--picture .el-upload-list__item-thumbnail {
    width: 190px;
  }

  ::v-deep .el-table .cell {
    white-space: nowrap;
  }
}
</style>